/**
 * 获取父级主键数组
 * @param id
 * @param pk
 * @param tree
 * @param pid
 * @param field
 * @param relation
 * @param fields
 * @returns {Array}
 */
export const toTreeParents = (id, pk, tree, pid = 'pid', field = null, relation = [], fields = []) => {
  if (!id) {
    return relation
  }
  findParent(id, pk, tree, pid, field, relation, fields)
  const item = relation[relation.length - 1]
  if (item.pid > 0) {
    toTreeParents(item.pid, pk, tree, pid, field, relation, fields)
  } else {
    fields.reverse()
    relation.reverse()
  }
  return field ? fields : relation
}

/**
 * 禁用树选项
 * @param tree
 * @param field
 * @param value
 * @param disabled
 * @returns {Array}
 */
export const treeDisableItem = (tree, field, value, disabled = false) => {
  const data = []; const length = tree.length
  for (let i = 0; i < length; i++) {
    const item = tree[i]
    item['disabled'] = disabled || item[field] === value
    if (item.children) {
      item['children'] = treeDisableItem(item.children, field, value, item['disabled'])
    }
    data.push(item)
  }
  return data
}

/**
 * 筛选保留子级节点
 * @param ids
 * @param lists
 * @param pid
 * @returns {*}
 */
export const filterChildrenIds = (ids, lists, pid = 'pid') => {
  const length = lists.length
  for (let i = 0; i < length; i++) {
    const item = lists[i]
    const index = ids.indexOf(item[pid])
    if (index >= 0) {
      ids.splice(index, 1)
    }
    if (item.children) {
      filterChildrenIds(ids, item.children)
    }
  }
  return ids
}

// 查找父级项目
function findParent(id, pk, tree, pid, field, relation, fields) {
  for (let i = 0; i < tree.length; i++) {
    const item = tree[i]
    if (item.children && item.children.length > 0) {
      findParent(id, pk, item.children, pid, field, relation, fields)
    }
    if (item[pk] === id) {
      if (field) {
        fields.push(item[field])
      }
      relation.push(item)
      break
    }
  }
}
